/**
 * 自营广告
 */
import throttle from 'lodash/throttle';

var LOGURL = '/action_log/',
    ads = [],
    winClientSize = _getWinSize();

/**
 * cookie获取
 */
function _getCookie(key) {
  var arr,reg = new RegExp("(^| )"+ key + "=([^;]*)(;|$)");
  if(arr = document.cookie.match(reg)) return unescape(arr[2]);
  else return null;
}

/**
 * 添加监听事件
 */
function _addEvent(elem, type, handler) {
  if (elem.addEventListener) {
      elem.addEventListener(type, handler, false);
      return handler;
  } else if (elem.attachEvent) {
      var wrapper = function () {
        var event = window.event;
        event.target = event.srcElement;
        handler.call(elem, event);
      };
      elem.attachEvent('on' + type, wrapper);
      return wrapper;
  }
}

/**
 * 获取元素标签属性
 */
function _getAttribute(elem, attr) {
  if (!elem) return '';

  var attribute = elem.getAttribute(attr);

  return attribute? attribute : '';
}

/**
 * 设置元素属性
 */
function _setAttribute(elem, attr, value) {
  if (!elem) return;

  elem.setAttribute(attr, value);
}

/**
 * 获取窗口尺寸
 */
function _getWinSize() {
  if (window.innerHeight && window.innerWidth) {
     return {
       winWidth: window.innerWidth,
       winHeight: window.innerHeight
     };
  }
  if (document.documentElement && document.documentElement.clientHeight
    && document.documentElement.clientWidth) {
    return {
      winWidth: document.documentElement.clientWidth,
      winHeight: document.documentElement.clientHeight
    }
  }
}

/**
 * 元素是否完全在可视区域
 */
function _isAllInView(elem) {
  var rect = elem.getBoundingClientRect();

  return (
      rect.top >= 0 &&
      rect.left >= 0 &&
      rect.bottom <= winClientSize.winHeight &&
      rect.right <= winClientSize.winWidth
  );
}

/**
 * 元素是否主要内容在可视区
 */
function _isContentInView(elem) {
  var rect = elem.getBoundingClientRect();

  return (
      rect.top + 16 < winClientSize.winHeight &&
      rect.bottom > 16
  );
}

/**
 * 简易ajax
 */
function _ajax(params) {
  var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"),
      type = (params.type || 'get').toUpperCase(),
      url = params.url,
      data = params.data;

  if (!url) return;

  var dataArr = [];
  for (var k in data) {
    dataArr.push(k + '=' + data[k]);
  }

  if (type === 'GET') {
    url = url + '?' + dataArr.join('&') + '&_=' + Math.random();
    xhr.open(type, url, true);
    xhr.send();
  } else {
    xhr.open(type, url, true);
    xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.send(dataArr.join('&'));
  }

  xhr.onload = function() {
    if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
      params.success && params.success.call(xhr, xhr.responseText);
    }
  }
}

/**
 * 自有平台事件上报
 */
function _reporter(params) {
  _ajax({
    url: LOGURL,
    type: 'POST',
    data: {
      value: params.value,
      tag: 'embeded_ad',
      label: params.label,
      is_ad_event: '1',
      log_extra: params.extra,
      category: 'web',
      utm_source: _getCookie('utm_source'),
      csrfmiddlewaretoken: _getCookie('csrftoken')
    },
    success: function(res) {}
  });

  // 自有统计上报
  window.ttAnalysis && window.ttAnalysis.send('event', {ev: 'feed_ad_' + params.label});
}

/**
 * 第三方监控上报
 */
function _thridReporter(url) {
  var img = new Image();
  img.src = url;
}

/**
 * 广告展现，事件上报
 */
function _adShowHandle() {
  var params;

  for (var i = 0, len = ads.length; i < len; i++) {
    var add_tmp = ads[i];

    if (_isContentInView(add_tmp)) {
      if (_getAttribute(add_tmp, 'ad_show') != 1) {
        _setAttribute(add_tmp, 'ad_show', 1);
        params = {
          value: _getAttribute(add_tmp, 'ad_id'),
          extra: _getAttribute(add_tmp, 'ad_extra'),
          label: 'show',
          track: _getAttribute(add_tmp, 'ad_track')
        };
        params.track && _thridReporter(params.track);
        _reporter(params);
      }
    } else {
      _setAttribute(add_tmp, 'ad_show', 0);
    }
  }
}

/**
 * riot ie8 兼容
 */
function _getAdExtra(add) {
  if (!add) return '';
  var addExtra = add.querySelectorAll('#ad_extra')[0];
  return addExtra.innerText || '';
}

// 滚动监听
_addEvent(window, 'scroll', throttle(function() {
  _adShowHandle();
}, 150));

_addEvent(window, 'resize', throttle(function(){
  winClientSize = _getWinSize();
}, 150));

/**
 * 接口暴露
 */
function ttSetAds(adsList) {
  ads = adsList;
  _adShowHandle();
};
function ttSendMsg(params) {
  _reporter(params);
};

export  {
  ttSetAds,
  ttSendMsg
};



// WEBPACK FOOTER //
// ./~/byted-toutiao-pc-business-components/components/feed/src/_data/tAdMonitor.js
